<template>
	<div class="code-box">
		<el-button class="copy-button" size="small" type="primary" @click="clickCopy(code)">复制</el-button>
		<highlightjs class="code-js" autodetect :code="code" ></highlightjs>
	</div>
</template>

<script>
	import {
		ElMessage
	} from 'element-plus'
	export default {
		props: {
			code: {
				type: [String, Number],
				export: ''
			}
		},
		name: 'dev-highlightjs',
		data() {
			return {

			}
		},
		methods:{
			clickCopy(val) {
				// createElement() 方法通过指定名称创建一个元素
				var copyInput = document.createElement("input");
				//val是要复制的内容
				copyInput.setAttribute("value", val);
				document.body.appendChild(copyInput);
				copyInput.select();
				try {
					var copyed = document.execCommand("copy");
					if (copyed) {
						document.body.removeChild(copyInput);
						ElMessage.success('复制成功')
					}
				} catch {
					ElMessage.error('复制失败，请检查浏览器兼容')
				}
			
			
			}
		}
	}
</script>

<style>
	.code-box {
		position: relative;
		white-space: pre-wrap;
	}
	code{
		font-family: Menlo,Monaco,Consolas,Courier,monospace !important;
	}

	.copy-button {
		position: absolute;
		top: 10px;
		right: 10px;
	}
	.code-js{
		white-space: pre-wrap;
	}
</style>
